package com.gzc.just.play.last.war.allinone.controller;

import com.gzc.just.play.last.war.allinone.orchestration.ServerDependencyGraph;
import com.gzc.just.play.last.war.allinone.orchestration.ServerHealthChecker;
import com.gzc.just.play.last.war.allinone.orchestration.ServerOrchestrator;
import com.gzc.just.play.last.war.allinone.orchestration.ServerState;
import com.gzc.just.play.last.war.allinone.orchestration.ServerStateManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务器编排监控控制器
 * 提供Web界面和API查看服务器状态
 */
@Controller
public class OrchestrationController {
    
    @Autowired
    private ServerOrchestrator serverOrchestrator;
    
    @Autowired
    private ServerStateManager stateManager;
    
    @Autowired
    private ServerDependencyGraph dependencyGraph;
    
    @Autowired
    private ServerHealthChecker healthChecker;
    
    /**
     * 服务器状态仪表板页面
     * @param model 模型
     * @return 页面名称
     */
    @GetMapping("/orchestration")
    public String orchestrationDashboard(Model model) {
        model.addAttribute("serverStates", stateManager.getAllServerStates());
        model.addAttribute("dependencyGraph", dependencyGraph.getDependencyGraphString());
        model.addAttribute("startupOrder", dependencyGraph.getStartupOrder());
        model.addAttribute("parallelGroups", dependencyGraph.getParallelGroups());
        model.addAttribute("isAllReady", serverOrchestrator.isAllServersReady());
        model.addAttribute("isRunning", serverOrchestrator.isRunning());
        
        return "orchestration-dashboard";
    }
    
    /**
     * 获取服务器状态API
     * @return 服务器状态映射
     */
    @GetMapping("/api/servers/status")
    @ResponseBody
    public Map<String, Object> getServerStatus() {
        Map<String, Object> response = new HashMap<>();
        
        response.put("servers", stateManager.getAllServerStates());
        response.put("allReady", serverOrchestrator.isAllServersReady());
        response.put("isRunning", serverOrchestrator.isRunning());
        response.put("healthCheckerRunning", healthChecker.isRunning());
        
        return response;
    }
    
    /**
     * 获取特定服务器状态API
     * @param serverName 服务器名称
     * @return 服务器状态详情
     */
    @GetMapping("/api/servers/{serverName}/status")
    @ResponseBody
    public Map<String, Object> getServerStatus(@PathVariable String serverName) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 将服务器名称转换为枚举值
            String enumName = serverName.toUpperCase() + "_SERVER";
            com.gzc.just.play.last.war.allinone.orchestration.ServerType serverType = 
                com.gzc.just.play.last.war.allinone.orchestration.ServerType.valueOf(enumName);
            
            ServerState state = stateManager.getServerState(serverType);
            long lastHealthCheck = healthChecker.getLastHealthCheckTime(serverType);
            long stateDuration = stateManager.getStateDuration(serverType);
            
            response.put("name", serverName);
            response.put("state", state);
            response.put("port", serverType.getPort());
            response.put("lastHealthCheck", lastHealthCheck);
            response.put("stateDuration", stateDuration);
            response.put("dependencies", dependencyGraph.getDependencies(serverType));
            response.put("dependents", dependencyGraph.getDependents(serverType));
            
        } catch (IllegalArgumentException e) {
            response.put("error", "Unknown server: " + serverName);
        }
        
        return response;
    }
    
    /**
     * 获取依赖关系图API
     * @return 依赖关系图
     */
    @GetMapping("/api/servers/dependencies")
    @ResponseBody
    public Map<String, Object> getDependencyGraph() {
        Map<String, Object> response = new HashMap<>();
        
        response.put("graph", dependencyGraph.getDependencyGraphString());
        response.put("startupOrder", dependencyGraph.getStartupOrder());
        response.put("parallelGroups", dependencyGraph.getParallelGroups());
        
        return response;
    }
    
    /**
     * 获取系统概览API
     * @return 系统概览
     */
    @GetMapping("/api/system/overview")
    @ResponseBody
    public Map<String, Object> getSystemOverview() {
        Map<String, Object> response = new HashMap<>();
        
        Map<String, ServerState> serverStates = stateManager.getAllServerStates();
        
        int totalServers = serverStates.size();
        long runningServers = serverStates.values().stream()
                .filter(state -> state == ServerState.RUNNING || state == ServerState.READY || state == ServerState.CONNECTED)
                .count();
        
        long errorServers = serverStates.values().stream()
                .filter(state -> state == ServerState.ERROR || state == ServerState.UNHEALTHY)
                .count();
        
        response.put("totalServers", totalServers);
        response.put("runningServers", runningServers);
        response.put("errorServers", errorServers);
        response.put("allReady", serverOrchestrator.isAllServersReady());
        response.put("isRunning", serverOrchestrator.isRunning());
        
        return response;
    }
}